package com.zlf.mvc.controller;

import com.zlf.constant.CrowdConstant;
import com.zlf.entity.Menu;
import com.zlf.service.api.MenuService;
import com.zlf.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：张利锋
 * @date ：Created in 2020/11/18 19:42
 * @description： TOOD
 * @version: 1.0
 */
@Controller
//@RestController 等于@Controller+@ResponseBody  使用此注解表示所有方法都注解@ResponseBody
public class MenuController {
    @Autowired
    MenuService menuService;

    @RequestMapping("/menu/save")
    @ResponseBody
    public ResultEntity<String> saveMenu(Menu menu) {
        if ("".equals(menu.getName())){
            return ResultEntity.failed(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }
        menuService.saveMenu(menu);
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/menu/update")
    @ResponseBody
    public ResultEntity<String> editMenu(Menu menu) {
        if ("".equals(menu.getName())){
            return ResultEntity.failed(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }
        menuService.editMenu(menu);
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/menu/remove")
    @ResponseBody
    public ResultEntity<String> removeMenu(@RequestParam("id") Integer id) {
        menuService.removeMenu(id);
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/menu/get/whole/tree")
    @ResponseBody
    public ResultEntity<Menu> getWholeTree() {
        //1.查询全部的menu对象
        List<Menu> menus = menuService.getAll();
        //2.声明一个变量存储找到的根节点
        Menu root = null;
        //3.创建map对象来存储id和menu对象的对应关系以便于查找父节点
        Map<Integer, Menu> menuMap = new HashMap<>();
        //4.遍历menus填充menumap
        for (Menu menu : menus) {
            menuMap.put(menu.getId(), menu);
        }
        //5.遍历list查找根节点，组装父子对象
        for (Menu menu : menus) {
            //6.获取当前menu对象的pid属性值
            Integer pid = menu.getPid();
            //7.如果pid为null，判定为根节点
            if (pid == null) {
                root = menu;
                //8.如果当前节点时根节点，则不往下执行
                continue;
            }
            //9.pid部位null，说明当前节点有父节点，根据pid找到map中对应的menu对象
            Menu father = menuMap.get(pid);
            //10.把当前字节的存入父节点的children中
            father.getChildren().add(menu);
        }
        return ResultEntity.successWithData(root);
    }

}
